using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;

using VSTalk.Engine.Core.Context;
using VSTalk.Model;
using VSTalk.Tools;

namespace VSTalk.Engine.ViewModel.ContactList
{
    public class TreeContactLayout : IContactListLayout, IListener
    {
        public static IModelContext ModelContext
        {
            get { return AppServices.Get<IModelContext>(); }
        }

        private ObservableCollection<ClientNodeViewModel> _clients = new ObservableCollection<ClientNodeViewModel>();

        private ISubscription _clientUnit;

        private bool _isActive;

        public ObservableCollection<ClientNodeViewModel> Clients
        {
            get { return _clients; }
            set
            {
                _clients = value;
                PropertyChanged.Notify(() => Clients);
            }
        }

        public void StartListen()
        {
            _clientUnit = ModelContext.Clients.HandleCollectionChanges(initialOrAdd: AddClientPresentation,
                    removed: RemoveClientPresentation);
        }

        public void StopListen()
        {
            _clientUnit.Unsubscribe();
        }

        private void AddClientPresentation(Client client)
        {
            var clientNodeViewModel = new ClientNodeViewModel(client);
            Clients.Add(clientNodeViewModel);
            clientNodeViewModel.StartListen();
        }

        private void RemoveClientPresentation(Client client)
        {
            var clientNodeViewModel = Clients.First(model => model.Model == client);
            clientNodeViewModel.StopListen();
            Clients.Remove(clientNodeViewModel);
        }

        public bool IsActive
        {
            get { return _isActive; }
            set
            {
                _isActive = value;
                PropertyChanged.Notify(() => IsActive);
            }
        }

        public void Deactivate()
        {
            IsActive = false;
        }

        public void Activate()
        {
            IsActive = true;
        }


        public event PropertyChangedEventHandler PropertyChanged;
    }
}